package net.thxjj.adminServer.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctiot.aep.mqmsgpush.sdk.IMsgConsumer;
import com.ctiot.aep.mqmsgpush.sdk.IMsgListener;
import com.ctiot.aep.mqmsgpush.sdk.MqMsgConsumer;
import net.thxjj.adminServer.entity.*;
import net.thxjj.adminServer.entity.aep.*;
import net.thxjj.adminServer.entity.aep.profilegc.ProfileGCInfoBean;
import net.thxjj.adminServer.entity.aep.profilegc.ProfileGCLoginBean;
import net.thxjj.adminServer.service.IDevLogService;
import net.thxjj.adminServer.service.IDeviceService;
import net.thxjj.adminServer.service.IProfileGCService;
import net.thxjj.adminServer.service.IProfileLogService;
import net.thxjj.adminServer.util.ParameterMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.logging.Logger;

@Service
public class NBServer {
    private static final java.util.logging.Logger logger = Logger.getLogger(NBServer.class.getCanonicalName());

    @Autowired
    private IDevLogService iDevLogService;

    @Autowired
    private IDeviceService iDeviceService;

    @Autowired
    private IProfileLogService iProfileLogService;
    @Autowired
    private IProfileGCService iProfileGCService;

    public void run() {
        String server = "msgpush.ctwing.cn:16651"; //消息服务地址
        String tenantId = Const.TENANTID;//租户ID
        String token = Const.TOKEN;//身份认证token串
        String certFilePath = ""; //直接填空字符串，CA证书，JDK已经内置相关根证书，无需指定

        //创建消息接收Listener
        IMsgListener msgListener = new IMsgListener() {

            @Override
            public void onMessage(String msg) {
                logger.info("aep message："+msg);
                JSONObject jsonObject = JSON.parseObject(msg);
                String prod_key = jsonObject.getString("productId");
                if(!Const.PRODUCT_ID.equals(prod_key) && !Const.PROFILE_PRODUCT_ID.equals(prod_key)&& !Const.PROFILE_PRODUCT_ID_GC.equals(prod_key)&& !Const.PROFILE_PRODUCT_ID_GC_2.equals(prod_key)){
                    return;
                }
                if(Const.PRODUCT_ID.equals(prod_key)){
                    insertData(msg);
                }else if(Const.PROFILE_PRODUCT_ID_GC.equals(prod_key) || Const.PROFILE_PRODUCT_ID_GC_2.equals(prod_key)){
                    insertProfileGCData(msg);
                }else{
                    insertProfileData(msg);
                }

            }
        };


        //创建消息接收类
        IMsgConsumer consumer = new MqMsgConsumer();
        try {
            //初始化
            /**
             * @param server  消息服务server地址
             * @param tenantId 租户Id
             * @param token    用户认证token
             * @param certFilePath 证书文件路径
             * @param topicNames   主题名列表，如果该列表为空或null，则自动消费该租户所有主题消息
             * @param msgListener 消息接收者
             * @return 是否初始化成功
             */
            consumer.init(server, tenantId, token, certFilePath, null, msgListener);

            //开始接收消息
            consumer.start();

            //程序退出时，停止接收、销毁
            //consumer.stop();
            //consumer.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("exit");
    }

    private void insertData(String msg){
        JSONObject jsonObject = JSON.parseObject(msg);
        if(msg.contains("eventReport")){
            DevLog devLog = JSONObject.parseObject(msg,DevLog.class);
            devLog.setCreateTime(jsonObject.getLongValue("timestamp"));
            iDevLogService.mqAddDevLog(devLog);
        }else if(msg.contains("dataReport")){
            long serviceId = jsonObject.getLongValue("serviceId");
            long timestamp = jsonObject.getLongValue("timestamp");
            String deviceId = jsonObject.getString("deviceId");
            if(serviceId==1){
                JSONObject result = jsonObject.getJSONObject("payload");
                SmokeData smokeData = JSONObject.parseObject(result.toJSONString(),SmokeData.class);
                smokeData.setDeviceId(deviceId);
                smokeData.setTimestamp(timestamp);
                iDevLogService.mqAddSmokeData(smokeData);
            }else if(serviceId == 2){
                JSONObject result = jsonObject.getJSONObject("payload");
                HeartData heartData = JSONObject.parseObject(result.toJSONString(),HeartData.class);
                heartData.setDeviceId(deviceId);
                heartData.setTimestamp(timestamp);
                iDevLogService.mqAddHeartData(heartData);
            }else if(serviceId == 3){
                JSONObject result = jsonObject.getJSONObject("payload");
                LoginData loginData = JSONObject.parseObject(result.toJSONString(),LoginData.class);
                loginData.setDeviceId(deviceId);
                loginData.setTimestamp(timestamp);
                iDevLogService.mqAddLoginData(loginData);
            }
        }else if(msg.contains("deviceOnlineOfflineReport")){
            String device_id = jsonObject.getString("deviceId");
            long time = jsonObject.getLongValue("timestamp");
            long eventType = jsonObject.getLongValue("eventType");
            ParameterMap parameterMap = new ParameterMap();
            parameterMap.put("device_id",device_id);
            if(eventType==1){
                parameterMap.put("online_at",time);
                iDeviceService.updateDeviceOnline(parameterMap);
            }else{
                parameterMap.put("offline_at",time);
                iDeviceService.updateDeviceOffline(parameterMap);
            }

        }
    }


    private void insertProfileGCData(String msg){
        JSONObject jsonObject = JSON.parseObject(msg);
        String messType = jsonObject.getString("messageType");
        if("dataReport".equals(messType)){

            long timestamp = jsonObject.getLongValue("timestamp");
            String deviceId = jsonObject.getString("deviceId");
            JSONObject result = jsonObject.getJSONObject("payload");
            JSONObject resulta = result.getJSONObject("serviceData");
            String serviceId = result.getString("serviceId");
            if("DeviceInfoReport".equals(serviceId)){
                ProfileGCLoginBean profileLoginData = JSONObject.parseObject(resulta.toJSONString(),ProfileGCLoginBean.class);
                profileLoginData.setTimestamp(timestamp);
                profileLoginData.setDeviceId(deviceId);
                iProfileGCService.mqAddLoginData(profileLoginData);
            }else if("DeviceDataUpdateReport".equals(serviceId)){
                ProfileGCInfoBean profileLog = JSONObject.parseObject(resulta.toJSONString(),ProfileGCInfoBean.class);
                profileLog.setTimestamp(timestamp);
                profileLog.setDeviceId(deviceId);
                iProfileGCService.mqAddDevLog(profileLog);
            }
        }
        else if(msg.contains("deviceOnlineOfflineReport")){
            String device_id = jsonObject.getString("deviceId");
            long time = jsonObject.getLongValue("timestamp");
            long eventType = jsonObject.getLongValue("eventType");
            ParameterMap parameterMap = new ParameterMap();
            parameterMap.put("device_id",device_id);
            if(eventType==1){
                parameterMap.put("online_at",time);
                iDeviceService.updateDeviceOnline(parameterMap);
            }else{
                parameterMap.put("offline_at",time);
                iDeviceService.updateDeviceOffline(parameterMap);
            }

        }
    }

    private void insertProfileData(String msg){
        JSONObject jsonObject = JSON.parseObject(msg);
        String messType = jsonObject.getString("messageType");
        if("dataReport".equals(messType)){

            long timestamp = jsonObject.getLongValue("timestamp");
            String deviceId = jsonObject.getString("deviceId");
            JSONObject result = jsonObject.getJSONObject("payload");
            JSONObject resulta = result.getJSONObject("serviceData");
            if(msg.contains("TAU")){
                ProfileLoginData profileLoginData = JSONObject.parseObject(resulta.toJSONString(),ProfileLoginData.class);
                profileLoginData.setTimestamp(timestamp);
                profileLoginData.setDeviceId(deviceId);
                LoginData loginData = new LoginData().setActive_time(profileLoginData.getActiveTime())
                        .setActive_time_flag(profileLoginData.getActiveTimeFlag())
                        .setDevice_type(profileLoginData.getDevice_Type())
                        .setDeviceId(profileLoginData.getDeviceId())
                        .setHardware_version(profileLoginData.getHardwareVersion())
                        .setIMEI(profileLoginData.getIMEI())
                        .setIMSI(profileLoginData.getIMSI())
                        .setManufacturer_name(profileLoginData.getManufacturer())
                        .setSoftware_version(profileLoginData.getFirmwareVersion())
                        .setTau(profileLoginData.getTAU())
                        .setTau_flag(profileLoginData.getTAU_Flag())
                        .setTimestamp(profileLoginData.getTimestamp());
                iProfileLogService.mqAddLoginData(loginData);
            }else{
                ProfileLog profileLog = JSONObject.parseObject(resulta.toJSONString(),ProfileLog.class);
                profileLog.setTimestamp(timestamp);
                profileLog.setDeviceId(deviceId);
                iProfileLogService.mqAddDevLog(profileLog);
            }
        }
      else if(msg.contains("deviceOnlineOfflineReport")){
            String device_id = jsonObject.getString("deviceId");
            long time = jsonObject.getLongValue("timestamp");
            long eventType = jsonObject.getLongValue("eventType");
            ParameterMap parameterMap = new ParameterMap();
            parameterMap.put("device_id",device_id);
            if(eventType==1){
                parameterMap.put("online_at",time);
                iDeviceService.updateDeviceOnline(parameterMap);
            }else{
                parameterMap.put("offline_at",time);
                iDeviceService.updateDeviceOffline(parameterMap);
            }

        }
    }
}
